#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import threading
import time
import serial
from location import gpsdatastruct as gds
from utils import converseTime


class GPSSerialListener(threading.Thread):
    def __init__(self, sername, baudrate):
        threading.Thread.__init__(self, name="GPSSerialListener")
        self.open(sername, baudrate)
        self.curdata = gds.GPSStruct()
        self.__rate = 1
        self.__callbacklist = []

    def __del__(self):
        self.__ser.close()

    def open(self, port, baudrate):
        '''串口连接'''
        timeout = None  # 超时时间设置，None代表永远等待操作
        self.__ser = serial.Serial(port, baudrate, timeout=timeout)  # 打开串口，并得到串口对象

        if self.__ser.isOpen:
            self.__ser.close()
            self.__ser.open()
        # print('GPS串口详情参数：', self.__ser)

    def explonti(self, data):
        temp = data.replace('\x00', '')
        if len(temp) > 7:
            lon1 = float(temp[0:3])
            lon2 = float(temp[3:]) / 60
            lon = lon1 + lon2
            self.curdata.setlon(lon)

    def explati(self, data):
        temp = data.replace('\x00', '')
        if len(temp) > 7:
            lat1 = float(temp[0:2])
            lat2 = float(temp[2:]) / 60
            lat = lat1 + lat2
            self.curdata.setlat(lat)

    def expdirection(self, data):
        temp = data.replace('\x00', '')
        if len(temp) > 0:
            self.curdata.setdirect(float(temp))

    def expmode(self, data):
        temp = data.replace('\x00', '')
        if len(temp) > 0:
            self.curdata.setmode(int(temp))

    def expaltitude(self, data):
        temp = data.replace('\x00', '')
        if len(temp) > 0:
            self.curdata.setalti(float(temp))

    def exputc(self, data):
        temp = data.replace('\x00', '')
        if len(temp) > 0:
            self.curdata.setutc(float(temp))

    def expvelocity(self, data):
        temp = data.replace('\x00', '')
        if len(temp) > 0:
            self.curdata.setvelocity((float(temp) * 1.852))

    def addcallbackobj(self, fun):
        try:
            self.__callbacklist.append(fun)
        except Exception as ex:
            print("exception%s" % ex)

    def run(self):
        buffer = ""
        while self.__ser.readable():
            try:
                s = time.time()
                data = self.__ser.read(
                    self.__ser.inWaiting())  # data = "$GNRMC,102345.00,A,3146.67035,N,11716.29160,E,0.027,,220422,,,
                # A,V*1F\n"
                buffer += data.decode("utf-8")

                head_rmc = buffer.rfind('$GNRMC')
                tail_gnrmc = buffer.find('\n', head_rmc)

                if tail_gnrmc != -1:  # 判断缓冲中是否有完整的数据，GGA
                    str_gnrmc = buffer[head_rmc:tail_gnrmc]
                    # print(str_gnrmc)

                    rmc_list = str_gnrmc.split(',')
                    if len(rmc_list) == 14:
                        if rmc_list[2] == "A":
                            self.exputc(rmc_list[9] + rmc_list[1])
                            self.explonti(rmc_list[5])
                            self.explati(rmc_list[3])
                            self.expmode("0")
                            self.expdirection("0")
                            self.expaltitude("0")
                            self.expvelocity(rmc_list[7])
                    buffer = buffer[tail_gnrmc + 1:len(buffer)]

                    if self.curdata:
                        # print("当前速度:  %f  KM/H" % self.curdata.velocity)
                        for part in self.__callbacklist:
                            # 117.27086983333334 31.777769666666668 260522083914.0 0.0037040000000000003
                            # self.curdata.utc = converseTime.conversionDataBaseTime(str(self.curdata.utc))
                            # self.curdata.utc = int(self.curdata.utc)
                            self.curdata.velocity = round(self.curdata.velocity, 2)
                            # self.curdata.latitude = float()
                            gpsdata = {'lontitude': self.curdata.lontitude, 'latitude': self.curdata.latitude, 'uploadtime': self.curdata.utc, 'velocity': self.curdata.velocity,'altitude':self.curdata.altitude}
                            part.handle(gpsdata)
                        self.curdata.reset()
                    sleep_time = 1 / self.__rate - (time.time() - s)
                    if sleep_time > 0:
                        time.sleep(sleep_time)
            except Exception as ex:
                print("exception%s" % ex)
                time.sleep(1)


if __name__ == '__main__':
    listener = GPSSerialListener("COM9", 115200)
    listener.start()

    while True:
        a = input("输入速度：")
        print(a)
        time.sleep(10)
